# Create your views here.
from django.db.models import Q
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from .sers import *
from django.core.paginator import Paginator
from .filters import UserFilter
from django_filters.rest_framework import DjangoFilterBackend
# from .models import *


# Create your views here.
class UserView(APIView):
    def post(self, request):
        user_ser = UserSerializers(data=request.data)
        print(user_ser)
        if user_ser.is_valid():
            user_ser.save()
            return Response({'message': '登录成功', 'code': 200})
        else:
            return Response({'message': '登录失败', 'code': 400})
    def get(self,request):
        user_list = User.objects.all()
        user_ser = UserSerializers(user_list,many=True)
        return Response(user_ser.data)



class ChaView(APIView):
    def post(self,request):
        gg = request.data.get('gg')
        ll = request.data.get('ll')
        page = request.data.get('p')
        print(page)
        if all([gt,lt]):

            user_lsit = User.objects.filter(payment__gte=gg).filter(payment__lte = ll)
        elif gt:

            user_lsit = User.objects.filter(payment__gte=gg)
        elif ll:

            user_lsit = User.objects.filter(payment__lte = ll)
        else:
            user_lsit = User.objects.all()
        # user_ser = UserSerializers(user_lsit,many=True)
        # return Response({'data':user_ser.data})
        pageinfo = Paginator(user_lsit, 2)
        book_info = pageinfo.page(int(page))
        book_list = [i for i in pageinfo.page_range]
        ser_foods = UserSerializers(book_info, many=True)
        res_data = {
            'all_page': pageinfo.num_pages,
            'data': ser_foods.data,
            'page': book_info.number,
            'page_list': book_list
        }
        return Response(status=200, data=res_data)



# 调用过滤器
class UserViewSet(ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializers
        filter_backends = (DjangoFilterBackend,)
        # filter_fields = ('payment')
        filter_class = UserFilter